/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

/*
 * Created on 12/07/2004
 *
 */

package au.com.lastweekend.jim.io.jpeg;

import org.apache.log4j.Logger;

import au.com.lastweekend.jim.io.jpeg.write.JpegTransform;
import au.com.lastweekend.jim.io.jpeg.write.JpegTransform.Coordinate;

/**
 * @author grant@lastweekend.com.au
 * @version $Id: ScanComponent.java,v 1.3 2006/01/28 05:05:40 ggardner Exp $
 * 
 */
@SuppressWarnings("PMD.AvoidUsingShortType")
public class ScanComponent {

    private static final Logger LOG = Logger.getLogger(ScanComponent.class);
    private final byte componentID;
    private final int horizontalSamplingFactor;
    private final int verticalSamplingFactor;
    private HuffmanTable acHuffmanTable;
    private HuffmanTable dcHuffmanTable;
    private int dcPredictor = 0;

    private AbstractDCTBlock[][] coefficients;
    private JpegTransform transform;

    // Fixed length working arrays, used and re-used for DCTBlock operations
    // theoretically saving time for object creation and initialisation.
    // Be aware that old values will be in here, so the whole array needs to be
    // processed.
    private short[] workingValues = new short[63];
    private byte[] workingIndexes = new byte[63];
    private int[][] workingDCTMatrix = new int[8][8];

    private Coordinate transformedSamplingFactors;
    private Coordinate transformedSampleDimensions;

    public ScanComponent(Scan scan, byte componentID, int horizontalSamplingFactor, int verticalSamplingFactor) {

        this.componentID = componentID;
        this.horizontalSamplingFactor = horizontalSamplingFactor;
        this.verticalSamplingFactor = verticalSamplingFactor;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Initialising Scan Component: scan=" + scan + "componentID=" + componentID + "hSF="
                    + horizontalSamplingFactor + "vSF=" + verticalSamplingFactor);
        }
    }

    public byte getComponentID() {

        return componentID;
    }

    /**
     * @param decoder
     */
    public void setDCDecoder(HuffmanTable decoder) {

        dcHuffmanTable = decoder;

    }

    /**
     * @param decoder
     */
    public void setACDecoder(HuffmanTable decoder) {

        acHuffmanTable = decoder;

    }

    public int getHorizontalSamplingFactor() {

        return horizontalSamplingFactor;
    }

    public int getVerticalSamplingFactor() {

        return verticalSamplingFactor;
    }

    public void readMCU(int mcuX, int mcuY, JpegBitBuffer bitBuffer) throws JpegProcessingException {

        for (int v = 0; v < verticalSamplingFactor; v++) {
            int y = mcuY * verticalSamplingFactor + v;
            for (int h = 0; h < horizontalSamplingFactor; h++) {
                int x = mcuX * horizontalSamplingFactor + h;

                readBlockCoefficients(x, y, bitBuffer);
            }

        }

    }

    private void readBlockCoefficients(int x, int y, JpegBitBuffer bitBuffer) throws JpegProcessingException {

        AbstractDCTBlock coefficients = new RunLengthEncodedDCTBlock();
        coefficients.readCoefficients(this, bitBuffer);
        this.coefficients[x][y] = coefficients;
        dcPredictor = coefficients.getDCCoefficient();
    }

    /**
     * 
     * @param mcuColumns
     * @param mcuRows
     */
    public void initialiseScan(int mcuColumns, int mcuRows) {

        int horizontalSampleBlocks = mcuColumns * horizontalSamplingFactor;
        int verticalSampleBlocks = mcuRows * verticalSamplingFactor;

        coefficients = new AbstractDCTBlock[horizontalSampleBlocks][verticalSampleBlocks];
        dcPredictor = 0;
        LOG.debug("Initialised Scan");
    }

    /**
     * 
     */
    public void restartDecoder() {

        dcPredictor = 0;

    }

    /**
     * @param mcuX
     * @param mcuY
     * @param bitOutput
     * @throws JpegProcessingException
     */
    public void writeMCU(int mcuX, int mcuY, JpegBitOutput bitOutput) throws JpegProcessingException {

        for (int v = 0; v < transformedSamplingFactors.getHeight(); v++) {
            int y = mcuY * transformedSamplingFactors.getHeight() + v;
            for (int h = 0; h < transformedSamplingFactors.getWidth(); h++) {
                int x = mcuX * transformedSamplingFactors.getWidth() + h;
                writeBlockCoefficients(x, y, bitOutput);

            }

        }

    }

    /**
     * @param x
     * @param y
     * @param bitOutput
     * @throws JpegProcessingException
     */
    private void writeBlockCoefficients(int x, int y, JpegBitOutput bitOutput) throws JpegProcessingException {

        // x and y are in the NEW co-ordinate space, having been transformed as
        // appropriate in the MCU loop.
        // To find which co-efficient to transform we need to do a reverse
        // transformation.

        Coordinate blockLocation = transform.reverseTransform(x, y, transformedSampleDimensions.getWidth(),
                transformedSampleDimensions.getHeight());

        AbstractDCTBlock sampleBlock = getBlockCoefficients(blockLocation.getX(), blockLocation.getY());
        AbstractDCTBlock newBlock = transform.transformBlock(this, sampleBlock);
        newBlock.writeCoefficients(this, bitOutput);
        dcPredictor = newBlock.getDCCoefficient();

    }

    /**
     * @param transform
     */
    public void initialiseTransform(JpegTransform transform) {

        dcPredictor = 0;
        this.transform = transform;
        transformedSamplingFactors = transform.transform(horizontalSamplingFactor, verticalSamplingFactor);
        transformedSampleDimensions = transform.transform(coefficients.length, coefficients[0].length);

    }

    /**
     * 
     */
    public void restartEncoder() {

        dcPredictor = 0;
    }

    public HuffmanTable getDCHuffmanTable() {

        return dcHuffmanTable;
    }

    public int getDCPredictor() {

        return dcPredictor;
    }

    public byte[] getWorkingIndexes() {

        return workingIndexes;
    }

    public short[] getWorkingValues() {

        return workingValues;
    }

    public HuffmanTable getACHuffmanTable() {

        return acHuffmanTable;
    }

    public AbstractDCTBlock getBlockCoefficients(int x, int y) {

        return coefficients[x][y];
    }

    public int[][] getWorkingDCTMatrix() {

        return workingDCTMatrix;
    }

}